import 'package:get/get.dart';
import '../model/app_file_desc.dart';

late AppFileSelectionController _controller;

AppFileSelectionController get currentSelection {
  return _controller;
}

AppFileSelectionController get findSelection {
  try {
    return Get.find<AppFileSelectionController>();
  } catch (e) {
    _controller = AppFileSelectionController();
    return Get.put(_controller, permanent: false);
  }
}

class AppFileSelectionController extends GetxController {
  final _tag = "AppFileSelectionController";
  final selectedFileDescSet = <AppFileDesc>{}.obs;
  final selectedMode = false.obs;

  bool get isSelectMode => selectedMode.value;
  set isSelectMode(bool value) => selectedMode.value = value;

  int get selectedCount => selectedFileDescSet.length;

  bool get isSelectEmpty => selectedFileDescSet.isEmpty;

  List<AppFileDesc> get selectedFiles => selectedFileDescSet.toList();

  void selectedFile(AppFileDesc fileDesc) {
    if (selectedMode.value) {
      if (selectedFileDescSet.contains(fileDesc)) {
        selectedFileDescSet.remove(fileDesc);
      } else {
        selectedFileDescSet.add(fileDesc);
      }
      selectedFileDescSet.refresh();
    }
  }

  void selectedList(List<AppFileDesc> fileDescList) {
    if (selectedMode.value) {
      selectedFileDescSet.clear();
      selectedFileDescSet.addAll(fileDescList);
      selectedFileDescSet.refresh();
    }
  }

  void cancelSelected() {
    if (selectedMode.value) {
      selectedFileDescSet.clear();
      selectedFileDescSet.refresh();
    }
  }

  bool isSelected(AppFileDesc fileDesc) {
    if (!isSelectMode) {
      return false;
    }
    return selectedFileDescSet.contains(fileDesc);
  }

  bool isSelectAll(List<AppFileDesc> fileDescList) {
    return selectedFileDescSet.length == fileDescList.length;
  }

  void enterSelectMode() {
    selectedMode.value = true;
    selectedFileDescSet.clear();
    selectedFileDescSet.refresh();
  }

  void exitSelectMode() {
    selectedMode.value = false;
    selectedFileDescSet.clear();
    selectedFileDescSet.refresh();
  }
}
